"""
添加扫货账号对话框
"""
from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel,
                           QLineEdit, QPushButton, QSpinBox, QComboBox,
                           QMessageBox)
from PyQt6.QtCore import Qt
from PyQt6.QtGui import QFont
from .login_dialog import LoginDialog
from com.db.scan_account_manager import ScanAccountManager
import logging
from datetime import datetime

# 配置日志
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

class AddScanAccountDialog(QDialog):
    """添加扫货账号对话框"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.account_manager = ScanAccountManager()
        self.setWindowTitle("新增账号")
        self.setFixedSize(500, 400)
        self.setWindowFlags(Qt.WindowType.Dialog | Qt.WindowType.WindowCloseButtonHint)
        self.setup_ui()
        
    def setup_ui(self):
        """初始化UI"""
        layout = QVBoxLayout(self)
        layout.setSpacing(20)
        layout.setContentsMargins(20, 20, 20, 20)
        
        # uu token输入框
        token_layout = QHBoxLayout()
        token_label = QLabel("uu token")
        token_label.setFixedWidth(80)
        self.token_input = QLineEdit()
        self.token_input.setPlaceholderText("手动输入或点击右方登录按钮自动获取")
        login_btn = QPushButton("登录悠悠")
        login_btn.setStyleSheet("""
            QPushButton {
                padding: 5px 10px;
                background-color: #409eff;
                color: white;
                border: none;
                border-radius: 2px;
                font-size: 12px;
            }
            QPushButton:hover {
                background-color: #66b1ff;
            }
        """)
        token_layout.addWidget(token_label)
        token_layout.addWidget(self.token_input)
        token_layout.addWidget(login_btn)
        
        # 账号名称输入框
        name_layout = QHBoxLayout()
        name_label = QLabel("账号名称")
        name_label.setFixedWidth(80)
        self.name_input = QLineEdit()
        self.name_input.setPlaceholderText("默认为您悠悠账号昵称，也可随意填写你觉得好记的名称")
        name_layout.addWidget(name_label)
        name_layout.addWidget(self.name_input)
        
        # 标签选择
        tag_layout = QHBoxLayout()
        tag_label = QLabel("标签")
        tag_label.setFixedWidth(80)
        self.tag_combo = QComboBox()
        self.tag_combo.setPlaceholderText("请选择或输入标签")
        self.tag_combo.setEditable(True)
        tag_layout.addWidget(tag_label)
        tag_layout.addWidget(self.tag_combo)
        
        # 使用频率限制
        freq_layout = QHBoxLayout()
        freq_label = QLabel("使用频率限制")
        freq_label.setFixedWidth(80)
        self.freq_spin = QSpinBox()
        self.freq_spin.setRange(1, 100)
        self.freq_spin.setValue(20)
        freq_unit = QLabel("秒使用一次")
        freq_layout.addWidget(freq_label)
        freq_layout.addWidget(self.freq_spin)
        freq_layout.addWidget(freq_unit)
        freq_layout.addStretch()
        
        # 是否启用
        status_layout = QHBoxLayout()
        status_label = QLabel("是否启用")
        status_label.setFixedWidth(80)
        self.status_combo = QComboBox()
        self.status_combo.addItems(["是", "否"])
        status_layout.addWidget(status_label)
        status_layout.addWidget(self.status_combo)
        status_layout.addStretch()
        
        # 按钮区域
        btn_layout = QHBoxLayout()
        btn_layout.addStretch()
        
        cancel_btn = QPushButton("取消")
        cancel_btn.setStyleSheet("""
            QPushButton {
                padding: 5px 15px;
                background-color: white;
                color: #606266;
                border: 1px solid #dcdfe6;
                border-radius: 2px;
                font-size: 12px;
                min-width: 60px;
            }
            QPushButton:hover {
                color: #409eff;
                border-color: #c6e2ff;
                background-color: #ecf5ff;
            }
        """)
        
        confirm_btn = QPushButton("确定")
        confirm_btn.setStyleSheet("""
            QPushButton {
                padding: 5px 15px;
                background-color: #409eff;
                color: white;
                border: none;
                border-radius: 2px;
                font-size: 12px;
                min-width: 60px;
            }
            QPushButton:hover {
                background-color: #66b1ff;
            }
        """)
        
        btn_layout.addWidget(cancel_btn)
        btn_layout.addWidget(confirm_btn)
        
        # 添加所有布局
        layout.addLayout(token_layout)
        layout.addLayout(name_layout)
        layout.addLayout(tag_layout)
        layout.addLayout(freq_layout)
        layout.addLayout(status_layout)
        layout.addStretch()
        layout.addLayout(btn_layout)
        
        # 连接信号
        cancel_btn.clicked.connect(self.reject)
        confirm_btn.clicked.connect(self.accept)
        login_btn.clicked.connect(self.on_login)
        
    def on_login(self):
        """登录悠悠获取token"""
        try:
            logger.debug("点击了登录按钮，准备显示登录对话框")
            dialog = LoginDialog(self)
            dialog.show()  # 先显示窗口
            logger.debug("登录对话框显示完成")
            result = dialog.exec()
            logger.debug(f"登录对话框返回结果: {result}")
            
            if result == QDialog.DialogCode.Accepted:
                logger.debug("登录成功")
                # 获取登录数据
                account_data = getattr(dialog, 'account_data', None)
                if account_data:
                    logger.debug(f"登录数据: {account_data}")
                    # 更新UI显示
                    self.token_input.setText(account_data.get('token', ''))
                    self.name_input.setText(account_data.get('nickname', ''))
                    
                    # 记录从 LoginDialog 获取的 account_data 中的 UK 值
                    uk_from_login = account_data.get('uk', '')
                    logger.debug(f"从 LoginDialog 获取的 account_data 中的 UK 值: {uk_from_login}")
                    logger.debug(f"LoginDialog 中的 account_data 完整内容: {account_data}")
                    
                    # 保存登录数据以便后续保存
                    # 确保字段名称与get_form_data方法中期望的一致
                    self.login_data = {
                        'token': account_data.get('token', ''),
                        'uu_user_id': account_data.get('uu_user_id', 0),
                        'user_id': account_data.get('user_id', 0),
                        'nickname': account_data.get('nickname', ''),
                        'deviceId': account_data.get('device_id', ''),
                        'device_id': account_data.get('device_id', ''),
                        'uk': uk_from_login,  # 使用从 LoginDialog 获取的 UK 值
                        'avatar': None,
                        'steam_id': None,
                        'device_info': {}
                    }
                    logger.debug(f"保存到 self.login_data 的 UK 值: {self.login_data.get('uk', '无UK值')}")
                    QMessageBox.information(self, "提示", "登录验证成功")
                else:
                    logger.error("未获取到登录数据")
                    QMessageBox.warning(self, "错误", "未获取到登录数据")
            else:
                logger.debug("登录取消或失败")
        except Exception as e:
            logger.error(f"显示登录对话框时发生错误: {str(e)}")
            QMessageBox.warning(self, "错误", f"显示登录对话框时发生错误: {str(e)}")
            
    def get_form_data(self):
        """获取表单数据"""
        if not hasattr(self, 'login_data'):
            return None
            
        logger.debug(f"登录数据: {self.login_data}")
            
        # 使用登录数据作为基础
        account_data = {
            'name': self.name_input.text().strip(),
            'uu_token': self.token_input.text().strip(),
            'min_interval': self.freq_spin.value(),
            'status': 1 if self.status_combo.currentText() == "是" else 0,
            'tags': [self.tag_combo.currentText().strip()] if self.tag_combo.currentText().strip() else [],
            
            # 用户基本信息
            'device_id': self.login_data.get('deviceId'),
            'uu_user_id': self.login_data.get('uu_user_id'),  
            'avatar': self.login_data.get('avatar'),  
            'nickname': self.login_data.get('nickname'),  
            'steam_id': self.login_data.get('steam_id'),  
            
            # 设备信息
            'uk': self.login_data.get('uk'),
            'device_info': self.login_data.get('device_info', {}),  
            
            # UK 值的调试信息已移除，不需要保存到数据库
            
            # 状态信息
            'alive': 1,  
            'alive_times': 0,  
            'create_at': str(int(datetime.now().timestamp() * 1000)),
            'update_at': int(datetime.now().timestamp() * 1000)
        }
        
        logger.debug(f"账号数据: {account_data}")
        return account_data
